// 存储用户数据
const userData = {
  name: "朋友",
  pressureLevel: 0, // 0-30: 轻度, 31-60: 中度, 61-100: 重度
  lastAssessment: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000), // 3天前
  assessmentHistory: [
    { date: "周一", level: 35 },
    { date: "周二", level: 42 },
    { date: "周三", level: 50 },
    { date: "周四", level: 45 },
    { date: "周五", level: 38 },
    { date: "周六", level: 25 },
    { date: "周日", level: 30 },
  ],
};

// 压力评估问题库
const assessmentQuestions = [
  {
    question: "在过去的一周里，你是否经常感到无法控制生活中重要的事情？",
    options: ["从不", "偶尔", "经常", "总是"],
  },
  {
    question: "在过去的一周里，你是否感到自信能够处理个人问题？",
    options: ["非常自信", "比较自信", "不太自信", "完全不自信"],
    reverse: true, // 反向计分
  },
  {
    question: "在过去的一周里，你是否感到事情正按照你的期望发展？",
    options: ["总是", "经常", "偶尔", "从不"],
    reverse: true, // 反向计分
  },
  {
    question: "在过去的一周里，你是否发现自己无法应对所有需要完成的事情？",
    options: ["从不", "偶尔", "经常", "总是"],
  },
  {
    question: "在过去的一周里，你是否能够成功地处理让你烦恼的事情？",
    options: ["总是", "经常", "偶尔", "从不"],
    reverse: true, // 反向计分
  },
  {
    question: "在过去的一周里，你是否感到自己能够控制工作中的各种情况？",
    options: ["总是", "经常", "偶尔", "从不"],
    reverse: true, // 反向计分
  },
  {
    question: "在过去的一周里，你是否发现自己会因为情绪问题而影响睡眠？",
    options: ["从不", "偶尔", "经常", "总是"],
  },
  {
    question: "在过去的一周里，你是否感到压力积累到无法排解的程度？",
    options: ["从不", "偶尔", "经常", "总是"],
  },
  {
    question: "在过去的一周里，你是否对未来感到焦虑或不安？",
    options: ["从不", "偶尔", "经常", "总是"],
  },
  {
    question: "在过去的一周里，你是否有足够的时间放松和照顾自己？",
    options: ["总是", "经常", "偶尔", "从不"],
    reverse: true, // 反向计分
  },
];

// 压力级别建议
const pressureSuggestions = {
  light: [
    "建议每天进行5-10分钟的深呼吸练习",
    "尝试在工作间隙聆听'雨声'环境音",
    "晚间可以玩1-2局像素小鸟游戏放松心情",
  ],
  medium: [
    "建议进行15-20分钟的呼吸冥想练习",
    "尝试连续进行2局飞刀结界游戏缓解压力",
    "晚间聆听'森林'环境音辅助入眠",
    "适当安排周末完全放松的时间",
  ],
  heavy: [
    "建议寻求专业心理咨询师的帮助和指导",
    "每天安排30分钟的专注放松时间",
    "尝试连续进行3-4局解压游戏",
    "与朋友或家人分享你的感受和压力",
    "考虑适当调整工作节奏和生活方式",
  ],
};

// 音效路径
const soundPaths = {
  rain: "assets/sounds/rain.mp3",
  forest: "assets/sounds/forest.mp3",
  fire: "assets/sounds/fire.mp3",
  ocean: "assets/sounds/ocean.mp3",
};

// 当前选中的音效
let currentSound = null;

// DOM元素
document.addEventListener("DOMContentLoaded", function () {
  // 初始化页面数据
  initializeApp();

  // 绑定导航事件
  document.querySelectorAll(".nav-item").forEach((item) => {
    item.addEventListener("click", function () {
      navigateTo(this.dataset.page);
    });
  });

  // 绑定压力评估事件
  document
    .getElementById("startAssessment")
    .addEventListener("click", startAssessment);
  document
    .getElementById("closeAssessment")
    .addEventListener("click", closeModal);
  document.getElementById("closeResults").addEventListener("click", closeModal);

  // 绑定游戏选择事件
  document.querySelectorAll(".game-card").forEach((card) => {
    card.addEventListener("click", function () {
      launchGame(this.dataset.game);
    });
  });

  // 绑定音效选择事件
  document.querySelectorAll(".asmr-card").forEach((card) => {
    card.addEventListener("click", function () {
      toggleSound(this.dataset.sound);
      updateActiveSound(this);
    });
  });

  // 播放暂停按钮
  document
    .getElementById("playPauseBtn")
    .addEventListener("click", togglePlayPause);

  // 音量控制
  document
    .getElementById("volumeSlider")
    .addEventListener("input", adjustVolume);

  // 查看完整报告
  document
    .getElementById("viewFullReport")
    .addEventListener("click", viewFullReport);

  // 初始化压力趋势图表
  initializeChart();
});

// 初始化应用数据
function initializeApp() {
  // 设置用户名
  document.getElementById("userName").textContent = userData.name;

  // 设置压力指数
  updatePressureLevel(userData.pressureLevel);

  // 设置上次评估时间
  const lastAssessmentDays = Math.floor(
    (new Date() - userData.lastAssessment) / (24 * 60 * 60 * 1000)
  );
  document.getElementById(
    "lastAssessment"
  ).textContent = `上次评估: ${lastAssessmentDays}天前`;

  // 设置欢迎消息
  setWelcomeMessage();
}

// 设置欢迎消息
function setWelcomeMessage() {
  const hour = new Date().getHours();
  let message = "";

  if (hour < 6) {
    message = "夜深了，记得休息哦";
  } else if (hour < 9) {
    message = "早安，开始新的一天吧";
  } else if (hour < 12) {
    message = "上午好，工作顺利吗？";
  } else if (hour < 14) {
    message = "中午好，记得午休哦";
  } else if (hour < 18) {
    message = "下午好，来杯咖啡提提神？";
  } else if (hour < 22) {
    message = "晚上好，放松一下如何？";
  } else {
    message = "夜深了，准备休息了吗？";
  }

  document.getElementById("welcomeMessage").textContent = message;
}

// 更新压力指数
function updatePressureLevel(level) {
  document.getElementById("pressureValue").textContent = level;
  document.getElementById("pressureLevel").style.width = `${level}%`;

  // 根据压力级别设置背景颜色
  let bgColor = "";
  if (level <= 30) {
    bgColor = "var(--light-pressure)";
  } else if (level <= 60) {
    bgColor = "var(--medium-pressure)";
  } else {
    bgColor = "var(--high-pressure)";
  }

  document.getElementById("pressureLevel").style.backgroundColor = bgColor;
}

// 导航功能
function navigateTo(page) {
  // 移除所有导航项的活跃状态
  document.querySelectorAll(".nav-item").forEach((item) => {
    item.classList.remove("active");
  });

  // 设置当前导航项为活跃
  document
    .querySelector(`.nav-item[data-page="${page}"]`)
    .classList.add("active");

  // 这里可以实现实际页面切换，但当前为单页演示
  console.log(`导航到: ${page}`);

  // 为完整应用可添加页面切换逻辑
  // 例如：
  // document.querySelectorAll('.page').forEach(p => p.classList.add('hidden'));
  // document.getElementById(`${page}Page`).classList.remove('hidden');
}

// 启动游戏
function launchGame(game) {
  switch (game) {
    case "flappy":
      window.location.href = "像素小鸟.html";
      break;
    case "knife":
      window.location.href = "躲避飞刀.html";
      break;
    case "bubble":
    case "sand":
      alert("该游戏即将推出，敬请期待！");
      break;
    default:
      console.log("未知游戏");
  }
}

// 开始压力评估
function startAssessment() {
  // 显示评估模态框
  document.getElementById("assessmentModal").classList.add("active");

  // 重置评估状态
  currentQuestionIndex = 0;
  userAnswers = [];

  // 显示问题容器，隐藏结果容器
  document.querySelector(".question-container").classList.remove("hidden");
  document.getElementById("resultsContainer").classList.add("hidden");

  // 加载第一个问题
  loadQuestion(0);
}

// 当前问题索引和用户答案
let currentQuestionIndex = 0;
let userAnswers = [];

// 加载问题
function loadQuestion(index) {
  if (index < assessmentQuestions.length) {
    const question = assessmentQuestions[index];

    // 更新问题文本
    document.getElementById("questionText").textContent = question.question;

    // 更新进度条
    const progress = ((index + 1) / assessmentQuestions.length) * 100;
    document.getElementById("assessmentProgress").style.width = `${progress}%`;
    document.getElementById("questionCounter").textContent = `${index + 1}/${
      assessmentQuestions.length
    }`;

    // 清除之前的选项状态
    document.querySelectorAll(".option-btn").forEach((btn) => {
      btn.classList.remove("selected");
    });

    // 绑定选项点击事件
    const optionButtons = document.querySelectorAll(".option-btn");
    for (let i = 0; i < optionButtons.length; i++) {
      optionButtons[i].textContent = question.options[i];
      optionButtons[i].onclick = function () {
        selectOption(i, question.reverse);
      };
    }
  } else {
    // 所有问题回答完毕，显示结果
    showResults();
  }
}

// 选择选项
function selectOption(value, isReverse) {
  // 高亮选中的选项
  document.querySelectorAll(".option-btn").forEach((btn) => {
    btn.classList.remove("selected");
  });
  document.querySelectorAll(".option-btn")[value].classList.add("selected");

  // 计算得分 (0-3分，反向题反转)
  let score = isReverse ? 3 - value : value;
  userAnswers.push(score);

  // 延迟切换到下一题，形成过渡效果
  setTimeout(() => {
    currentQuestionIndex++;
    loadQuestion(currentQuestionIndex);
  }, 500);
}

// 显示评估结果
function showResults() {
  // 计算总分并转换为0-100的压力指数
  const totalPossibleScore = assessmentQuestions.length * 3; // 最高每题3分
  const userScore = userAnswers.reduce((sum, score) => sum + score, 0);
  const pressurePercentage = Math.round((userScore / totalPossibleScore) * 100);

  // 隐藏问题容器，显示结果容器
  document.querySelector(".question-container").classList.add("hidden");
  document.getElementById("resultsContainer").classList.remove("hidden");

  // 设置结果分数
  document.getElementById("resultScore").textContent = pressurePercentage;

  // 设置压力级别
  let pressureLevel;
  let suggestionList;

  if (pressurePercentage <= 30) {
    pressureLevel = "轻度压力";
    suggestionList = pressureSuggestions.light;
    document.querySelector(".score-circle").style.backgroundColor =
      "var(--light-pressure)";
  } else if (pressurePercentage <= 60) {
    pressureLevel = "中度压力";
    suggestionList = pressureSuggestions.medium;
    document.querySelector(".score-circle").style.backgroundColor =
      "var(--medium-pressure)";
  } else {
    pressureLevel = "重度压力";
    suggestionList = pressureSuggestions.heavy;
    document.querySelector(".score-circle").style.backgroundColor =
      "var(--high-pressure)";
  }

  document.getElementById("resultLevel").textContent = pressureLevel;

  // 填充建议列表
  const suggestionsElement = document.getElementById("suggestionsList");
  suggestionsElement.innerHTML = "";

  suggestionList.forEach((suggestion) => {
    const li = document.createElement("li");
    li.textContent = suggestion;
    suggestionsElement.appendChild(li);
  });

  // 更新用户数据
  userData.pressureLevel = pressurePercentage;
  userData.lastAssessment = new Date();

  // 更新今日压力指数显示
  updatePressureLevel(pressurePercentage);
  document.getElementById("lastAssessment").textContent = `上次评估: 今天`;

  // 更新压力历史数据（在实际应用中，这里会保存到数据库）
  const today = new Date();
  const weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"][
    today.getDay()
  ];
  userData.assessmentHistory.push({
    date: weekday,
    level: pressurePercentage,
  });

  // 如果历史数据超过7天，删除最旧的
  if (userData.assessmentHistory.length > 7) {
    userData.assessmentHistory.shift();
  }

  // 更新图表
  updateChart();
}

// 关闭模态框
function closeModal() {
  document.getElementById("assessmentModal").classList.remove("active");
}

// 切换音效
function toggleSound(sound) {
  const audio = document.getElementById("backgroundAudio");

  // 如果点击当前正在播放的音效，则停止播放
  if (currentSound === sound && !audio.paused) {
    audio.pause();
    currentSound = null;
    document.querySelector(".play-icon").classList.remove("hidden");
    document.querySelector(".pause-icon").classList.add("hidden");
    return;
  }

  // 设置新的音效源
  audio.src = soundPaths[sound];
  audio.volume = document.getElementById("volumeSlider").value / 100;
  audio.play().catch((e) => console.error("音频播放失败:", e));

  currentSound = sound;

  // 更新播放按钮状态
  document.querySelector(".play-icon").classList.add("hidden");
  document.querySelector(".pause-icon").classList.remove("hidden");
}

// 更新当前活跃的音效卡片
function updateActiveSound(element) {
  // 移除所有卡片的活跃状态
  document.querySelectorAll(".asmr-card").forEach((card) => {
    card.classList.remove("active");
  });

  // 设置当前卡片为活跃
  if (currentSound) {
    element.classList.add("active");
  }
}

// 切换播放/暂停
function togglePlayPause() {
  const audio = document.getElementById("backgroundAudio");
  const playIcon = document.querySelector(".play-icon");
  const pauseIcon = document.querySelector(".pause-icon");

  if (!currentSound) return;

  if (audio.paused) {
    audio.play();
    playIcon.classList.add("hidden");
    pauseIcon.classList.remove("hidden");
  } else {
    audio.pause();
    playIcon.classList.remove("hidden");
    pauseIcon.classList.add("hidden");
  }
}

// 调整音量
function adjustVolume() {
  const audio = document.getElementById("backgroundAudio");
  const volume = document.getElementById("volumeSlider").value;
  audio.volume = volume / 100;
}

// 查看完整报告
function viewFullReport() {
  alert("完整的压力趋势报告功能即将上线！");
}

// 初始化图表
function initializeChart() {
  const ctx = document.getElementById("pressureChart").getContext("2d");

  window.pressureChart = new Chart(ctx, {
    type: "line",
    data: {
      labels: userData.assessmentHistory.map((item) => item.date),
      datasets: [
        {
          label: "压力指数",
          data: userData.assessmentHistory.map((item) => item.level),
          borderColor: "rgba(160, 184, 205, 1)",
          backgroundColor: "rgba(160, 184, 205, 0.2)",
          tension: 0.3,
          fill: true,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false,
        },
      },
      scales: {
        y: {
          beginAtZero: true,
          max: 100,
          grid: {
            color: "rgba(0, 0, 0, 0.05)",
          },
        },
        x: {
          grid: {
            display: false,
          },
        },
      },
    },
  });
}

// 更新图表
function updateChart() {
  window.pressureChart.data.labels = userData.assessmentHistory.map(
    (item) => item.date
  );
  window.pressureChart.data.datasets[0].data = userData.assessmentHistory.map(
    (item) => item.level
  );
  window.pressureChart.update();
}
